<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="title"
    width="1000"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <el-tabs
      v-model="activeName"
      type="card"
      class="demo-tabs"
      :before-leave="beforeLeave"
    >
      <el-tab-pane label="供应商基础信息" :name="0" v-if="handleType == 'add'">
        <template #label>
          <span class="custom-tabs-label">
            <span>供应商基础信息</span><span class="text-red-500 text-lg">*</span>
          </span>
        </template>
        <div class="header-title my-4">供应商基础信息</div>
        <Basic
          ref="basicRef"
          v-model="supplierForm"
          :options="supplierOptions"
          :custom_sku="form.custom_sku"
        ></Basic>
        <div class="header-title my-4">联系人信息</div>
        <el-table
          :data="supplierForm.contact"
          border
          style="width: 100%"
          height="200"
          :row-class-name="rowClassName"
        >
          <el-table-column prop="default_account" label="是否默认" :min-width="80">
            <template #default="{ row, $index }">
              <el-radio
                v-model="row.default_account"
                :label="1"
                @change="handleCheck($index)"
                >默认</el-radio
              >
            </template>
          </el-table-column>
          <el-table-column prop="name" label="联系人姓名" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.name" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="job" label="联系人职位" min-width="120">
            <template #default="{ row }">
              <VSelect
                v-model="row.job_type"
                placeholder="职位类型"
                :options="supplierOptions.job_type"
                select
                class="w-full"
              />
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="电话" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.phone" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="fax" label="传真" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.fax" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column field="tel" label="手机号" :min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.tel" placeholder="手机号"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.email" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="qq" label="QQ" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.qq" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="wangwang" label="旺旺" min-width="120">
            <template #default="{ row }">
              <el-input v-model="row.wangwang" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="操作" width="120" fixed="right">
            <template #default="{ row, $index }">
              <el-button type="primary" link @click="addContact()">新增</el-button>
              <el-button type="danger" link @click="deleteContact($index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="flex justify-between items-center">
          <div class="header-title my-4">
            资质证明
            <span class="text-[#999] text-sm font-normal"
              >（三证合一证件不需上传税务登记和组织机构代码证，文件类型只能是jpg/png/jpeg/pdf，不超过5M）</span
            >
          </div>
          <el-button type="primary" @click="uploadAttachment">上传附件</el-button>
        </div>
        <el-table
          :data="supplierForm.proveArray"
          border
          style="width: 100%"
          height="200"
          :row-class-name="rowClassName"
        >
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="date" label="附件类型">
            <template #default="{ row }">
              {{ row.type_name }}
            </template>
          </el-table-column>
          <el-table-column prop="date" label="附件名称">
            <template #default="{ row }">
              {{ row.filename }}
            </template>
          </el-table-column>
          <el-table-column prop="date" label="操作" width="140">
            <template #default="{ row, $index }">
              <el-button type="primary" link @click="downloadProveArray(row, $index)"
                >下载</el-button
              >
              <el-button type="danger" link @click="deleteProveArray($index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="财务信息" :name="1" v-if="handleType == 'add'">
        <template #label>
          <span class="custom-tabs-label">
            <span>财务信息</span><span class="text-red-500 text-lg">*</span>
          </span>
        </template>
        <el-form
          ref="supplierFormRef"
          :model="supplierForm"
          :rules="rules"
          label-align="right"
          label-width="110"
          label-position="top"
        >
          <Finance
            ref="financeRef"
            v-model="supplierForm.finance"
            :options="supplierOptions"
          ></Finance>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="供应商信息" :name="2">
        <template #label>
          <span class="custom-tabs-label">
            <span>供应商信息</span><span class="text-red-500 text-lg">*</span>
          </span>
        </template>
        <SupplierInfo
          ref="SupplierInfoRef"
          v-model="form"
          :order_exist="order_exist"
          :handleType="handleType"
          :disabled_default_supplier="disabled_default_supplier"
          :info="info"
          @autoFill="onAutoFill"
        ></SupplierInfo>
      </el-tab-pane>
      <el-tab-pane label="报关信息" :name="3">
        <template #label>
          <span class="custom-tabs-label">
            <span>报关信息</span><span class="text-red-500 text-lg">*</span>
          </span>
        </template>
        <!-- <div class="header-title mb-4">报关信息</div> -->
        <CustomsInfo
          ref="customsInfoRef"
          v-model="goods_sku_customs"
          :info="{
            ...info,
            supplier_name: fieldPermission(
              'supplier_name',
              form.supplier_name,
              form.supplier_code
            ),
            supplier_id: form.supplier_id,
          }"
          :order_exist="order_exist"
          :handleType="handleType"
        ></CustomsInfo>
      </el-tab-pane>
      <el-tab-pane label="欧英代产品信息" :name="4">
        <TradeAgent
          ref="TradeAgentRef"
          v-model="goods_sku_trade_agent"
          :info="{
            customs_en_name: goods_sku_customs.en_name,
            customs_cn_name: goods_sku_customs.cn_name,
            supplier_name: form.supplier_name,
            supplier_id: form.supplier_id,
            battery_voltage: goods_sku_customs.battery_voltage,
            battery_voltage_unit: goods_sku_customs.battery_voltage_unit,
          }"
          :handleType="handleType"
        ></TradeAgent>
      </el-tab-pane>
      <el-tab-pane label="产品加工说明" :name="5">
        <IdentificationProcessing
          v-model="goods_sku_identification_processing"
          :handleType="handleType"
        ></IdentificationProcessing>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button
        v-if="handleType != 'view'"
        type="primary"
        :loading="loading"
        @click="save(formRef)"
        >保 存</el-button
      >
      <template v-if="handleType == 'add'">
        <el-button type="primary" @click="handleToggle('prev')" v-if="activeName != 0"
          >上一项</el-button
        >
        <el-button type="primary" @click="handleToggle('next')" v-if="activeName != 5"
          >下一项</el-button
        >
      </template>
      <template v-else>
        <el-button type="primary" @click="handleToggle('prev')" v-if="activeName != 2"
          >上一项</el-button
        >
        <el-button type="primary" @click="handleToggle('next')" v-if="activeName != 5"
          >下一项</el-button
        >
      </template>
      <div
        v-if="permission_general && form.id && !info.is_add_sku && handleType == 'edit'"
        class="absolute bottom-0 right-2"
      >
        <el-button
          v-if="activeName == 2"
          type="primary"
          @click="handleRegionSave('goods_sku_supplier')"
          >保存供应商信息</el-button
        >
        <el-button
          v-if="activeName == 3"
          type="primary"
          @click="handleRegionSave('goods_sku_customs')"
          >保存报关信息</el-button
        >
        <el-button
          v-if="activeName == 4"
          type="primary"
          @click="handleRegionSave('goods_sku_trade_agent')"
          >保存欧英代信息</el-button
        >
        <el-button
          v-if="activeName == 5"
          type="primary"
          @click="handleRegionSave('goods_sku_identification_processing')"
          >保存产品加工说明</el-button
        >
      </div>
    </template>
  </el-dialog>
  <NativeUpload ref="NativeUploadRef" @uploadFile="addProve"></NativeUpload>
</template>
<script setup name="SupplierForm" lang="jsx">
import { reactive, toRefs, getCurrentInstance, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getBaseOptions, supplierCreate } from "@/api/index";
import { deepClone } from "@/utils/index";
import Basic from "@/components/Supplier/basicInfo/Basic";
import Finance from "@/components/Supplier/basicInfo/Finance";
import NativeUpload from "@/components/Supplier/NativeUpload";
import CustomsInfo from "@/components/Supplier/CustomsInfo.vue";
import IdentificationProcessing from "@/components/Supplier/IdentificationProcessing.vue";
import TradeAgent from "@/components/Supplier/TradeAgent.vue";
import SupplierInfo from "@/components/Supplier/SupplierInfo.vue";
import { changeOrderExist, getCustomsDetail } from "@/api/index.js";
import {
  change_order_category,
  oversea_location_category,
  customs_info_category,
} from "@/utils/data.js";
import { changeOrderSupplier } from "../../api.js";
import { downloadFile } from "@/utils/downloadFile.js";
import { goodsRegionSave } from "../../../api.js";
import { regionNameMap } from "../../../data.js";
import { handletTwiceConfirm } from "@/utils/product/index.js";
import useCommonStore from "@/store/modules/common";
import { fieldPermission } from "@/utils/permission.js";

const commonStore = useCommonStore();
const logisticsOptions = computed(() => {
  if (!commonStore.logisticsOptions) {
    commonStore.getLogisticsList();
  }
  return commonStore.logisticsOptions;
});

const { proxy } = getCurrentInstance();
const emit = defineEmits(["supplierList", "queryDetail"]);
const options = reactive(inject("options"));

const spu_data = reactive(inject("form"));

const props = defineProps({
  list: {
    type: Array,
    default: () => {
      return [];
    },
  },
  info: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const { list, info } = toRefs(props);

let form = ref({
  sku: [],
  supplier_name: "",
  purchase_link: "",
  is_default_supplier: 1,
  status: 1,
  unit_price_tax: "",
  unit_price: "",
  tax_rate: "",
  min_order_quantity: "",
  purchase_days: null,
  production_days: null,
  purchase_transportation_days: null,
  inventory_days: null,
  mpq_min_quantity: null,
  supplier_packing_quantity: null,
  invoice_tax_rate: 13,
});

// 供应商权限
const permission_general = computed(() => {
  return (window.BTN_AUTH || []).includes("/goods/task/product/general-info");
});

const data = reactive({
  formRef: null,
  visible: false,
  rules: {
    supplier_name: [{ required: true, message: "请选择供应商名称" }],
    min_order_quantity: [{ required: true, message: "请输入最小起订量/MOQ" }],
    purchase_days: [{ required: true, message: "采购天数不能为空" }],
    sku: [{ required: true, message: "请选择sku", trigger: "blur" }],
    unit_price: [{ required: true, message: "请输入采购未税报价" }],
    tax_rate: [{ required: true, message: "请输入供应商税点" }],
    is_refund_tax: [{ required: true, message: "请选择是否退税" }],
  },
  title: "",
  handleType: "",
  activeName: 0,
  goods_sku_customs: {}, // 新报关信息
  old_goods_sku_customs: {}, // 旧报关信息
  goods_sku_trade_agent: {}, // 欧英代产品信息
  goods_sku_identification_processing: [], // 产品标识及加工说明
  supplierForm: {}, // 供应商基础信息
  supplierOptions: {}, // 供应商枚举类
  is_skip: false, // 兼容赛盒同步信息 没有报关信息的判断
  order_exist: {
    exist: false,
  }, // 存在待审核的数据
  sourceData: null, // 原数据
  loading: false,
  disabled_default_supplier: false,
  load: false,
});

const {
  rules,
  visible,
  loading,
  formRef,
  title,
  handleType,
  activeName,
  goods_sku_customs,
  old_goods_sku_customs,
  goods_sku_trade_agent,
  goods_sku_identification_processing,
  supplierForm,
  supplierOptions,
  is_skip,
  order_exist,
  sourceData,
  disabled_default_supplier,
  load,
  // currencyInfo,
} = toRefs(data);

const statusMap = new Map([
  ["add", "新增并绑定供应商"],
  ["edit", "编辑供应商"],
  ["binding", "绑定供应商"],
  ["copy", "绑定供应商"],
  ["view", "查看供应商"],
]);

const countryMap = new Map([
  ["德国", "DE"],
  ["英国", "UK"],
  ["澳大利亚", "AU"],
  ["美国", "US"],
]);

const CUSTOMS_FILTER_KEY = [
  "cn_name",
  "declare_unit",
  "declare_elements",
  "tax_rebate_rate",
  "customs_code",
  "customs_quantity",
];

const open = async (row, type, sku, active) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  const data = row ? deepClone(row) : row;
  title.value = statusMap.get(type);
  handleType.value = type;
  if (type == "add") {
    initSupplierForm();
    supplierForm.value.basic.director_id = window.userInfo?.user?.user_id;
  }
  if (active) {
    activeName.value = active;
  } else {
    activeName.value = type == "add" ? 0 : 2;
  }

  order_exist.value = await checkChangeOrderExist();

  if ((type == "add" || type == "binding" || type == "copy") && order_exist.value.exist) {
    return ElMessageBox.confirm(
      "<商品资料变更单>存在待审核的数据,当前无法修改，请审核通过后再进行调整。",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
  }

  if (data) {
    form.value = Object.assign(
      {},
      {
        ...data,
        is_refund_tax_init: data.is_refund_tax, // 记录初始化值
        sku: data.sku,
        is_supplier_id_init: data.supplier_id,
      }
    );

    if (data.goods_sku_customs) {
      goods_sku_customs.value = Object.assign({}, data.goods_sku_customs);
      if (goods_sku_customs.value.goods_sku_customs_info?.length == 0) {
        goods_sku_customs.value.goods_sku_customs_info = [
          {
            customs_currency: "USD",
          },
        ];
      }
      if (!goods_sku_customs.value.declare_elements_list?.length) {
        goods_sku_customs.value.declare_elements_list = [{}];
      }

      old_goods_sku_customs.value = Object.assign({}, data.goods_sku_customs);

      if (goods_sku_customs.value.declare_elements_list?.length == 0) {
        goods_sku_customs.value.declare_elements_list = [
          {
            text: "",
          },
        ];
      }
      goods_sku_customs.value.battery_voltage_unit =
        goods_sku_customs.value.battery_voltage_unit || "V";
      goods_sku_customs.value.battery_capacity_unit =
        goods_sku_customs.value.battery_capacity_unit || "mAh";
    } else {
      data.goods_sku_customs = initCustomsInfo();
      goods_sku_customs.value = data.goods_sku_customs;
      is_skip.value = true;
    }

    sourceData.value = Object.assign({}, data);

    if (data.goods_sku_trade_agent) {
      goods_sku_trade_agent.value = Object.assign({}, data.goods_sku_trade_agent);
    }
    if (data.goods_sku_identification_processing?.length) {
      goods_sku_identification_processing.value = deepClone(
        data.goods_sku_identification_processing
      );
    }
  } else {
    form.value.custom_sku = sku;
    form.value.currency = "CNY";
    form.value.inspection_time = 0;

    if (info.value.sku_product_type != 2) {
      goods_sku_customs.value.customs_quantity = 1;
    }
    if (
      !goods_sku_customs.value.goods_sku_customs_info ||
      goods_sku_customs.value.goods_sku_customs_info?.length == 0
    ) {
      goods_sku_customs.value.goods_sku_customs_info = [
        {
          customs_currency: "USD",
        },
      ];
    }
    if (goods_sku_customs.value.declare_elements_list?.length == 0) {
      goods_sku_customs.value.declare_elements_list = [
        {
          text: "",
        },
      ];
    }

    if (!goods_sku_customs.value.declare_elements_list?.length) {
      goods_sku_customs.value.declare_elements_list = [{}];
    }

    goods_sku_customs.value.is_multi_platform = 0;
    goods_sku_customs.value.battery_voltage_unit = "V";
    goods_sku_customs.value.battery_capacity_unit = "mAh";
  }
  form.value.sku_product_type = info.value.sku_product_type;
  if (JSON.stringify(supplierOptions.value) == "{}") {
    getBaseOptionsList();
  }

  const is_default_supplier = list.value.findIndex(
    (i) => i.is_default_supplier && i.id && !i.delete
  );
  if (
    is_default_supplier == -1 &&
    (type == "add" || type == "binding" || type == "copy")
  ) {
    disabled_default_supplier.value = true;
  } else {
    disabled_default_supplier.value = false;
  }

  if (!form.value.is_refund_tax && info.value.sku_product_type == 2) {
    form.value.is_refund_tax = 3;
  }
  visible.value = true;
};

const initSupplierForm = () => {
  supplierForm.value = {
    basic: {
      supplier_name: "",
      supplier_code: "",
      legal_person: "",
      social_code: "",
      register_time: "",
      branch_offices: "",
      company_nature: null,
      company_category: null,
      business_category: [],
      status: 1,
      department_id: null,
      director_id: null,
      supplier_level: null,
      tax_no: "",
      supplier_url: "",
      supplier_account: "",
      zip_code: "",
      company_address: "",
      company_area_id: [],
      company_area_name: [],
      factory_address_list: [
        {
          default_account: 1,
          factory_address: "",
          factory_area_id: [],
          factory_area_name: [],
        },
      ],
      return_address: "",
      return_area_id: [],
      return_area_name: [],
      is_blacklist: null,
      english_address: "",
      is_temporary: null,
      remark: "",
      department_name: "",
      director_name: "",
      develop_id: null,
      develop_name: "",
      supplier_en_name: "",
      is_investigate: null,
      is_has_finance: null,
      is_license_same: null,
      is_submit: 1,
    },
    purchase: {
      order_type: null,
      check_factory: null,
      factory_file: [],
      is_label: null,
      is_return: null,
      deliver_list: null,
      factory_deliver: null,
      change_main: null,
      oversea_purchase: "",
      fba_purchase: "",
      oversea_purchase_id: null,
      fba_purchase_id: null,
    }, // 采购设置
    finance: {
      finance: {
        order_type: null,
        period_id: null,
        period_name: null,
        payment_type: null,
        settlement_time: null,
        settlement_day: null,
        free_shipping: null,
        cod_type: null,
        free_amount: "",
        settlement_type: null,
      },
      collect: [
        {
          account_type: "",
          bank_id: "",
          payee: "",
          id_card: "",
          bank_address: "",
          bank_card: "",
          currency: "",
          tax_account: "",
          default_account: "",
          currency: "CNY",
        },
      ],
      invoice: {
        is_invoice: 1,
        invoice_type: null,
        invoice_person_seniority: null,
        invoice_person_type: null,
        invoice_address: "",
        finance_tax: 13,
        tax_time: "",
      },
    }, // 财务信息
    collect: {}, // 收款账户
    invoice: {}, // 开票设置
    contact: [
      {
        default_account: "",
        name: "",
        job: "",
        phone: "",
        fax: "",
        tel: "",
        email: "",
        qq: "",
        wangwang: "",
      },
    ], // 联系人
    proveArray: [], // 资质证明
    prove: {},
  };
};

const getBaseOptionsList = async () => {
  try {
    const res = await getBaseOptions({
      type: "supplier",
    });
    supplierOptions.value = res.data;
  } catch (e) {
    throw Error(e);
  }
};

const TradeAgentRef = ref();

const rowClassName = ({ row }) => {
  if (row.delete === 1) {
    return "hidden-row";
  }
  return "";
};

const basicRef = ref();
const financeRef = ref();
const customsInfoRef = ref();

const is_change_order_category = change_order_category.includes(
  info.value.spu_category[0]
);
const is_oversea_location_category = oversea_location_category.includes(
  info.value.spu_category[0]
);
// 保存
const save = async () => {
  const newForm = Object.assign({}, form.value);

  if (handleType.value == "add") {
    const validateAll = [basicRef, financeRef].reduce(
      (acc, cur) => (cur?.value ? acc.concat(cur.value.validate()) : acc),
      []
    );
    const validator = await Promise.all(validateAll);
    if (validator.some((d) => !d.success)) {
      const messages = validator.reduce((acc, cur) => {
        return cur.success
          ? acc
          : acc.concat([
              { name: cur.name, message: Object.values(cur.message).map((d) => d[0]) },
            ]);
      }, []);
      ElMessageBox({
        title: "提示",
        message: () => (
          <div>
            {messages.map((m) => {
              return (
                <div class="mb-3">
                  <div class="flex items-center">
                    <svg-icon class="mr-2" icon-class="QuestionFilled"></svg-icon>
                    {m.name}：
                  </div>
                  {m.message.map((d) => (
                    <div class="ml-6">{d.message}</div>
                  ))}
                </div>
              );
            })}
          </div>
        ),
      });
      return;
    }
  }

  newForm.goods_sku_customs = goods_sku_customs.value;
  newForm.goods_sku_trade_agent = goods_sku_trade_agent.value;

  let declare_elements = "";
  newForm.goods_sku_customs.declare_elements_list.forEach((item, index) => {
    const value = item.value || "";
    declare_elements += value;
    if (index < newForm.goods_sku_customs.declare_elements_list.length - 1) {
      declare_elements += "|";
    }
    item.sort = index;
    return item;
  });
  newForm.goods_sku_customs.declare_elements = declare_elements;

  if (order_exist.value.exist) {
    return handleConfirmMessage(
      "<商品资料变更单>存在待审核的数据，请审核通过后再进行调整。"
    );
  }

  // 校验
  const is_submit_validate_supplier = await submit_validate_supplier();
  const is_submit_validate_customs = await submit_validate_customs();

  if (!is_submit_validate_supplier && !is_submit_validate_customs) {
    return;
  }

  if (goods_sku_identification_processing.value.length) {
    newForm.goods_sku_identification_processing = goods_sku_identification_processing.value.filter(
      (i) => {
        if (i.product_identification && i.processing_method) {
          return i;
        }
      }
    );
    const processingMethodsUnique = areProcessingMethodsUnique(
      newForm.goods_sku_identification_processing
    );
    if (!processingMethodsUnique) {
      ElMessage.error("供应商+SKU+产品类型需要唯一");
      return;
    }
  }
  if (newForm.is_stock_prepare == 1 && Number(newForm.prepare_purchase_day) == 0) {
    return ElMessage.error("是否备料为是，则采购天数不能为0");
  }

  newForm.goods_sku_customs.goods_sku_customs_info = newForm.goods_sku_customs.goods_sku_customs_info.filter(
    (i) => {
      if (
        i.id ||
        i.platform_id ||
        i.country_id ||
        Number(i.customs_price) ||
        Number(i.clearance_price) ||
        i.customs_link
      ) {
        return i;
      }
    }
  );
  // 当物流属性，是否含有电池=是 电池类型 电池电压 电池容量必填
  const find_logistics_attributes = logisticsOptions.value.find(
    (i) => i.value == info.value.logistics_attributes && i.with_electricity == 1
  );
  if (find_logistics_attributes) {
    if (!newForm.goods_sku_customs.battery_type) {
      ElMessage.error("物流属性含有电池，请填写电池信息");
      return;
    }
    if (!newForm.goods_sku_customs.battery_voltage) {
      ElMessage.error("物流属性含有电池，请填写电池信息");
      return;
    }
    if (!newForm.goods_sku_customs.battery_capacity) {
      ElMessage.error("物流属性含有电池，请填写电池信息");
      return;
    }
  }

  loading.value = true;

  // 是否存在默认供应商
  const is_default_supplier = list.value.findIndex((i) => i.is_default_supplier && i.id);

  if (
    info.value.dev_status >= 4 &&
    info.value.dev_status != 5 &&
    is_change_order_category &&
    !info.value.is_combination &&
    ((newForm.is_refund_tax == 2 &&
      compareObjectValues(
        old_goods_sku_customs.value,
        goods_sku_customs.value,
        CUSTOMS_FILTER_KEY
      )) ||
      (newForm.is_refund_tax == 2 && newForm.is_refund_tax_init == 3) ||
      ((handleType.value == "add" || handleType.value == "copy") &&
        ((newForm.is_default_supplier && is_oversea_location_category) ||
          newForm.is_refund_tax == 2))) &&
    is_default_supplier > -1
  ) {
    await handleConfirmMessage(
      "SKU开发状态=通过，且绑定的供应商存在是否退税=退税；更换默认供应商，或者修改退税供应商的‘报关中文名’、‘报关单位’、‘规格型号’、‘海关编码’、‘退税率’、‘申报要素’，点击确认后，系统将自动生成变更单，审核通过后执行修改，是否确认修改？",
      async () => {
        await createChangeOrder(newForm);
      }
    );
    loading.value = false;
  } else {
    if (handleType.value == "add") {
      const res = await handleSupplierCreate(newForm);
      loading.value = false;
      emit("supplierList", res);
      close();
    } else {
      loading.value = false;
      emit("supplierList", newForm);
      close();
    }
  }
};

// 供应商信息校验必填
const submit_validate_supplier = async () => {
  return new Promise(async (resolve, reject) => {
    const newForm = Object.assign({}, form.value);
    if (!newForm.supplier_name && handleType.value == "binding") {
      ElMessage.error("请选择供应商");
      return;
    }
    if (!newForm.unit_price) {
      ElMessage.error("请输入报价(不含税单价)");
      return;
    }
    if (!newForm.purchase_days) {
      ElMessage.error("采购天数不能为空");
      return;
    }

    if (newForm.is_refund_tax == 2 && !newForm.tax_rate) {
      ElMessage.error("请输入供应商税点");
      return;
    }

    if (
      newForm.is_refund_tax == 2 &&
      (Number(newForm.tax_rate) > 13 || Number(newForm.tax_rate) == 0)
    ) {
      ElMessage.error("供应商税点必须维护>0,<=13的值");
      return;
    }

    if (newForm.is_refund_tax == 2 && Number(newForm.invoice_tax_rate) != 13) {
      ElMessage.error("发票税点必须为13");
      return;
    }
    if (
      form.value.unit_price &&
      form.value.unit_price_tax &&
      Number(form.value.unit_price) > Number(form.value.unit_price_tax)
    ) {
      ElMessage.error(" 采购含税价必须>=采购未税报价,请修改");
      return;
    }

    let massageArray = [];
    if (handleType.value === "binding" || handleType.value === "copy") {
      list.value.forEach((i) => {
        if (i.supplier_id == newForm.supplier_id) {
          massageArray.push(
            ` ${newForm.custom_sku} 已存在供应商：${newForm.supplier_name}`
          );
        }
      });
    }

    if (massageArray && massageArray.length) {
      return ElMessageBox({
        title: "提示",
        message: <div>{massageArray.map((d) => h("p", null, d))}</div>,
      });
    }
    resolve(true);
  });
};

// 报关信息校验必填
const submit_validate_customs = async () => {
  return new Promise(async (resolve, reject) => {
    if (info.value.sku_product_type != 2 && !is_skip.value) {
      // 报关信息
      if (!goods_sku_customs.value.cn_name) {
        ElMessage.error("请输入中文报关名称");
        return;
      }
      if (!goods_sku_customs.value.en_name) {
        ElMessage.error("请输入英文报关名称");
        return;
      }
      if (!goods_sku_customs.value.cn_material) {
        ElMessage.error("请输入中文报关材质");
        return;
      }
      if (!goods_sku_customs.value.customs_code) {
        ElMessage.error("请输入海关编码");
        return;
      }
      if (!goods_sku_customs.value.declare_unit) {
        ElMessage.error("请输入报关单位");
        return;
      }
      if (!goods_sku_customs.value.customs_quantity) {
        ElMessage.error("请输入规格数量");
        return;
      }
      if (!goods_sku_customs.value.tax_rebate_rate) {
        ElMessage.error("请输入退税率");
        return;
      }

      if (
        goods_sku_customs.value.is_multi_platform &&
        goods_sku_customs.value.goods_sku_customs_info.length < 2
      ) {
        return ElMessage.error("当'是否多国家售卖'=是，则清关信息维护至少两条及以上");
      }

      const platformCountryPairs = goods_sku_customs.value.goods_sku_customs_info
        .filter((item) => !item.delete && (item.platform_name || item.country_id))
        .map((item) => [item.platform_name, item.country_id].join("-"));

      const hasUniquePairs =
        new Set(platformCountryPairs).size === platformCountryPairs.length;

      if (!hasUniquePairs) {
        ElMessage.error("平台和国家的组合不能相同；");
        return;
      }
      // 当前分类不需要必填
      const is_customs_info_category = customs_info_category.includes(
        info.value.spu_category[0]
      );

      if (!is_customs_info_category) {
        let massageCustomsArray = [];
        goods_sku_customs.value.goods_sku_customs_info
          .filter((i) => !i.delete)
          .forEach((item, index) => {
            if (
              !item.delete &&
              ((info.value.sku_id &&
                (!item.country_id ||
                  Number(item.customs_price) <= 0 ||
                  !item.customs_link) &&
                !(
                  item.platform_name == "amazon" &&
                  (item.country_id == 262 || item.country_id == 6)
                )) ||
                (!info.value.sku_id &&
                  (item.platform_name || item.country_id) &&
                  (!item.country_id || !item.customs_price || !item.customs_link) &&
                  !(
                    item.platform_name == "amazon" &&
                    (item.country_id == 262 || item.country_id == 6)
                  )))
            ) {
              massageCustomsArray.push(
                `清关信息维护第${index + 1}条：国家/报关链接不允许为空,销售价必须>0。`
              );
            }
          });
        if (massageCustomsArray && massageCustomsArray.length) {
          return ElMessageBox({
            title: "提示",
            message: <div>{massageCustomsArray.map((d) => h("p", null, d))}</div>,
          });
        }
      }

      let massageDeclareArray = [];
      const skip_list = ["GTIN", "CAS", "其他"];
      goods_sku_customs.value.declare_elements_list.forEach((item, index) => {
        if (
          item.disabled &&
          item.text &&
          !skip_list.includes(item.text) &&
          (item.value === undefined || item.value === null || item.value === "")
        ) {
          massageDeclareArray.push(`申报要素维护项：第${index}项：值不能为空`);
        } else if (
          !item.disabled &&
          (!item.text ||
            item.value === undefined ||
            item.value === null ||
            item.value === "")
        ) {
          massageDeclareArray.push(`申报要素维护项：第${index}项：维护项和值不能为空`);
        }
      });

      if (massageDeclareArray && massageDeclareArray.length) {
        return ElMessageBox({
          title: "提示",
          message: <div>{massageDeclareArray.map((d) => h("p", null, d))}</div>,
        });
      }
    }
    if (form.value.is_refund_tax == 2) {
      const is_check = await ValidityDetection();
      if (is_check) {
        return ElMessage.error(
          "您所选海关编码的特殊商品标识=1，不支持退税，无法保存，请更换海关编码"
        );
      }
    }
    if (
      form.value.is_refund_tax == 2 &&
      Number(goods_sku_customs.value.tax_rebate_rate) == 0
    ) {
      return ElMessage.error("退税供应商的退税率必须>0，请确认");
    }

    resolve(true);
  });
};

// 比较对象属性值是否相同
const compareObjectValues = (oldObj, newObj, propertiesToCompare) => {
  for (let prop of propertiesToCompare) {
    if (oldObj[prop] !== newObj[prop]) {
      return true;
    }
  }
  return false;
};

const filterCustoms = (oldObj, newObj, propertiesToCompare) => {
  const obj = deepClone(newObj);
  for (let prop of propertiesToCompare) {
    obj[prop] = oldObj[prop];
  }
  return obj;
};

// 新增并绑定供应商
const handleSupplierCreate = async (newForm) => {
  return new Promise(async (resolve, reject) => {
    const formData = Object.assign({}, supplierForm.value);

    if (newForm.abatement_day) {
      formData.purchase.abatement_day = newForm.abatement_day;
    }
    if (formData.proveArray.length) {
      formData.proveArray.forEach((item) => {
        formData.prove[item.type] = [item.filepath];
      });
    }
    if (newForm.abatement_day) {
      formData.purchase.abatement_day = Number(newForm.abatement_day);
    }
    try {
      const res = await supplierCreate(formData);
      ElMessage.success("供应商创建成功");
      const obj = res.data;
      newForm.supplier_id = obj.s_id;
      newForm.supplier_name = obj.supplier_name;
      newForm.status = obj.status;
      newForm.audit_status = obj.audit_status;
      newForm.audit_status_name = obj.audit_status_name;
      newForm.purchase_type = obj.purchase_type;
      newForm.purchase_type_name = obj.purchase_type_name;
      newForm.supplier_manage = obj.director_id;
      newForm.supplier_manage_text = obj.director_name;
      resolve(newForm);
    } catch (e) {
      loading.value = false;
      reject(e);
      throw Error(e);
    }
  });
};

// 确认弹窗
const handleConfirmMessage = (message, confirmHandler) => {
  return new Promise((resolve, reject) => {
    ElMessageBox.confirm(message, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      beforeClose: (action, instance, done) => {
        if (action === "confirm") {
          instance.confirmButtonLoading = true; // 显示加载状态
          if (confirmHandler) {
            confirmHandler()
              .then(() => {
                resolve(); // 成功时 resolve
                done(); // 手动关闭弹窗
              })
              .catch((err) => {
                reject(err); // 失败时 reject
                done(); // 即使失败也要关闭弹窗
              })
              .finally(() => {
                instance.confirmButtonLoading = false; // 重置按钮状态
              });
          } else {
            done(); // 即使失败也要关闭弹窗
            instance.confirmButtonLoading = false; // 重置按钮状态
          }
        } else {
          reject("cancel"); // 取消操作
          done(); // 立即关闭弹窗
        }
      },
    }).catch(() => {}); // 捕获取消操作（已通过 reject 处理）
  });
};

// 判断供应商标识是否唯一
const areProcessingMethodsUnique = (arr) => {
  const filterArr = arr.filter((item) => !item.delete);

  const processingMethodsSet = new Set();
  for (const item of filterArr) {
    if (processingMethodsSet.has(item.product_identification)) {
      return false;
    }
    processingMethodsSet.add(item.product_identification);
  }
  return true;
};

const handleToggle = (type) => {
  if (type == "prev") {
    activeName.value--;
    if (activeName.value < 0) {
      activeName.value = 0;
    }
  } else if (type == "next") {
    activeName.value++;
    if (activeName.value > 5) {
      activeName.value = 5;
    }
  }
};

const close = () => {
  proxy.resetForm("formRef");
  form.value = {
    sku: "",
    supplier_name: "",
    purchase_link: "",
    is_default_supplier: 1,
    status: 1,
    unit_price_tax: "",
    unit_price: "",
    tax_rate: "",
    min_order_quantity: "",
    purchase_days: null,
    production_days: null,
    purchase_transportation_days: null,
    inventory_days: null,
    invoice_tax_rate: 13,
  };
  is_skip.value = false;
  goods_sku_customs.value = {};
  goods_sku_trade_agent.value = {};
  goods_sku_identification_processing.value = [];
  customsInfoRef.value.initComponent();
  order_exist.value = {
    exist: false,
  };
  visible.value = false;
};
defineExpose({ open });

// 新增联系人列表
const addContact = () => {
  supplierForm.value.contact.push({
    default_account: "",
    name: "",
    job: "",
    phone: "",
    fax: "",
    tel: "",
    email: "",
    qq: "",
    wangwang: "",
  });
};

// 删除联系人列表
const deleteContact = (index) => {
  if (supplierForm.value.contact.length <= 1) {
    ElMessage.error("至少保留一条");
    return;
  }
  supplierForm.value.contact.splice(index, 1);
};

// 上传附件
const NativeUploadRef = ref();
const uploadAttachment = () => {
  NativeUploadRef.value.open();
};

// 上传附件回调
const addProve = (obj) => {
  supplierForm.value.proveArray.push(obj);
};

// tab 切换
const beforeLeave = async (activeName, oldActiveName) => {
  if (activeName == 2 && oldActiveName == 1) {
    if (supplierForm.value.finance.invoice.supplier_tax_rate) {
      form.value.tax_rate = supplierForm.value.finance.invoice.supplier_tax_rate;
    }
    if (supplierForm.value.finance.invoice.finance_tax) {
      form.value.invoice_tax_rate = supplierForm.value.finance.invoice.finance_tax;
    }
    if (supplierForm.value.finance.invoice.is_invoice == 1) {
      form.value.is_refund_tax = 2;
    } else if (supplierForm.value.finance.invoice.is_invoice == 2) {
      form.value.is_refund_tax = 3;
      form.value.tax_rate = 0;
      form.value.invoice_tax_rate = 0;
    }
  }
};

const handleCheck = (rowIndex) => {
  supplierForm.value.contact.forEach((d, i) => {
    if (rowIndex === i) return;
    d.default_account = 2;
  });
};

// 检测有没有待审核变更单
const checkChangeOrderExist = async () => {
  const is_change_order_category = change_order_category.includes(
    info.value.spu_category[0]
  );

  if (!info.value.sku_id || !is_change_order_category) {
    return false;
  }
  try {
    const res = await changeOrderExist({
      sku_id: info.value.sku_id,
      change_type: 2,
    });
    const data = {
      exist: res.data.exist,
      content: `<商品资料变更单>存在待审核数据，请审核通过再进行调整；
           当前审核节点：${res.data.detail?.node_name}；当前审核人：${res.data.detail?.user_name}`,
    };
    return data;
  } catch (e) {
    throw Error(e);
  }
};

const immutableFields = [
  "id",
  "purchase_untaxed_price",
  "unit_price_tax",
  "is_refund_tax",
  "invoice_tax_rate",
  "unit_price",
  "tax_rate",
];
const customsFields = [
  "cn_name",
  "declare_unit",
  "declare_elements",
  "tax_rebate_rate",
  "customs_code",
  "customs_quantity",
];

// 生成变更单
const createChangeOrder = async (newForm) => {
  if (handleType.value === "add") {
    const res = await handleSupplierCreate(newForm);
    newForm = res;
  }

  try {
    const res = await changeOrderSupplier({
      sku_id: info.value.sku_id,
      goods_sku_supplier: [newForm],
    });
    ElMessage.success("生成变更单成功");

    if (
      handleType.value === "add" ||
      handleType.value === "binding" ||
      handleType.value === "copy"
    ) {
      loading.value = false;
      close();
    } else if (handleType.value === "edit") {
      if (newForm.is_refund_tax_init == 3 && newForm.is_refund_tax == 2) {
        immutableFields.forEach((field) => {
          if (sourceData.value.hasOwnProperty(field)) {
            newForm[field] = sourceData.value[field];
          }
        });
      }

      customsFields.forEach((field) => {
        if (sourceData.value.goods_sku_customs.hasOwnProperty(field)) {
          newForm.goods_sku_customs[field] = sourceData.value.goods_sku_customs[field];
        }
      });

      if (!newForm.id) {
        newForm.delete = 1;
      }
      loading.value = false;
      emit("supplierList", newForm);
      close();
    }
  } catch (e) {
    throw Error(e);
  }
};

// 海关编号合法判断
const ValidityDetection = () => {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await getCustomsDetail({
        customs_goods_code: goods_sku_customs.value.customs_code,
      });
      if (res.data?.special_identify == 1) {
        resolve(true);
      } else {
        resolve(false);
      }
    } catch (e) {
      reject(false); // 使用 reject 传递错误
      throw Error(e);
    }
  });
};

const downloadProveArray = (row, index) => {
  downloadFile(row.filepath, filename, false);
};

const deleteProveArray = (index) => {
  supplierForm.value.proveArray.splice(index, 1);
};

const handleRegionSave = async (edit_type, item) => {
  const data = {
    spu_id: spu_data.value.id,
    sku_id: info.value.sku_id || "",
    edit_type,
  };
  let supplier_info = null;
  const newForm = Object.assign({}, form.value);
  const goods_sku_supplier_id = form.value.id;
  // 是否存在默认供应商
  const is_default_supplier = list.value.findIndex((i) => i.is_default_supplier && i.id);
  switch (edit_type) {
    case "goods_sku_supplier":
      const is_submit_validate_supplier = await submit_validate_supplier();
      if (!is_submit_validate_supplier) {
        return;
      }
      await handletTwiceConfirm(
        `是否保存${regionNameMap.get(
          edit_type
        )}区域信息，点击确认则对该区域字段执行保存，并刷新当前编辑页面，请知悉。`
      );
      const goods_sku_supplier = Object.assign({}, form.value);
      delete goods_sku_supplier.goods_sku_customs;
      delete goods_sku_supplier.goods_sku_identification_processing;
      delete goods_sku_supplier.goods_sku_trade_agent;
      if (
        goods_sku_supplier.is_stock_prepare == 1 &&
        Number(goods_sku_supplier.prepare_purchase_day) == 0
      ) {
        return ElMessage.error("是否备料为是，则备料后采购天数不能为0");
      }
      if (
        info.value.dev_status >= 4 &&
        info.value.dev_status != 5 &&
        !info.value.is_combination &&
        is_change_order_category &&
        goods_sku_supplier.is_refund_tax == 2 &&
        goods_sku_supplier.is_refund_tax_init == 3 &&
        is_default_supplier > -1
      ) {
        await handleConfirmMessage(
          "SKU开发状态=通过，且绑定的供应商存在是否退税=退税；更换默认供应商，或者修改退税供应商的‘报关中文名’、‘报关单位’、‘规格型号’、‘海关编码’、‘退税率’、‘申报要素’，点击确认后，系统将自动生成变更单，审核通过后执行修改，是否确认修改？",
          async () => {
            await createChangeOrder(newForm);
          }
        );
        return;
      }
      supplier_info = {
        goods_sku_supplier,
      };
      break;
    case "goods_sku_customs":
      const is_submit_validate_customs = await submit_validate_customs();
      if (!is_submit_validate_customs) {
        return;
      }

      // 当物流属性，是否含有电池=是 电池类型 电池电压 电池容量必填
      const find_logistics_attributes = logisticsOptions.value.find(
        (i) => i.value == info.value.logistics_attributes && i.with_electricity == 1
      );
      if (find_logistics_attributes) {
        if (!goods_sku_customs.value.battery_type) {
          ElMessage.error("物流属性含有电池，请填写电池信息");
          return;
        }
        if (!goods_sku_customs.value.battery_voltage) {
          ElMessage.error("物流属性含有电池，请填写电池信息");
          return;
        }
        if (!goods_sku_customs.value.battery_capacity) {
          ElMessage.error("物流属性含有电池，请填写电池信息");
          return;
        }
      }

      await handletTwiceConfirm(
        `是否保存${regionNameMap.get(
          edit_type
        )}区域信息，点击确认则对该区域字段执行保存，并刷新当前编辑页面，请知悉。`
      );
      const data = Object.assign({}, goods_sku_customs.value);
      let declare_elements = "";
      data.declare_elements_list.forEach((item, index) => {
        const value = item.value;
        declare_elements += value;
        if (index < data.declare_elements_list.length - 1) {
          declare_elements += "|";
        }
        item.sort = index;
        return item;
      });
      data.declare_elements = declare_elements;
      data.goods_sku_customs_info = data.goods_sku_customs_info.filter((i) => {
        if (
          i.id ||
          i.platform_id ||
          i.country_id ||
          Number(i.customs_price) ||
          Number(i.clearance_price) ||
          i.customs_link
        ) {
          return i;
        }
      });
      if (
        info.value.dev_status >= 4 &&
        info.value.dev_status != 5 &&
        is_change_order_category &&
        !info.value.is_combination &&
        ((form.value.is_refund_tax == 2 &&
          compareObjectValues(
            old_goods_sku_customs.value,
            goods_sku_customs.value,
            CUSTOMS_FILTER_KEY
          )) ||
          (newForm.is_refund_tax == 2 &&
            newForm.is_refund_tax_init == 3 &&
            is_default_supplier > -1))
      ) {
        newForm.goods_sku_customs = data;
        await handleConfirmMessage(
          "SKU开发状态=通过，且绑定的供应商存在是否退税=退税；更换默认供应商，或者修改退税供应商的‘报关中文名’、‘报关单位’、‘规格型号’、‘海关编码’、‘退税率’、‘申报要素’，点击确认后，系统将自动生成变更单，审核通过后执行修改，是否确认修改？",
          async () => {
            await createChangeOrder(newForm);
          }
        );

        const filterData = filterCustoms(
          old_goods_sku_customs.value,
          goods_sku_customs.value,
          CUSTOMS_FILTER_KEY
        );
        supplier_info = {
          goods_sku_supplier: {
            goods_sku_customs: {
              ...data,
              ...filterData,
            },
            id: goods_sku_supplier_id,
          },
        };
      } else {
        supplier_info = {
          goods_sku_supplier: {
            goods_sku_customs: data,
            id: goods_sku_supplier_id,
          },
        };
      }
      break;
    case "goods_sku_trade_agent":
      await handletTwiceConfirm(
        `是否保存${regionNameMap.get(
          edit_type
        )}区域信息，点击确认则对该区域字段执行保存，并刷新当前编辑页面，请知悉。`
      );
      supplier_info = {
        goods_sku_supplier: {
          id: form.value.id,
          goods_sku_trade_agent: goods_sku_trade_agent.value,
        },
      };
      break;
    case "goods_sku_identification_processing":
      let identification_processing = deepClone(
        goods_sku_identification_processing.value
      );

      if (identification_processing.length) {
        identification_processing = identification_processing.filter((i) => {
          if (i.product_identification && i.processing_method) {
            return i;
          }
        });
        const processingMethodsUnique = areProcessingMethodsUnique(
          identification_processing
        );
        if (!processingMethodsUnique) {
          ElMessage.error("供应商+SKU+产品类型需要唯一");
          return;
        }
      }
      await handletTwiceConfirm(
        `是否保存${regionNameMap.get(
          edit_type
        )}区域信息，点击确认则对该区域字段执行保存，并刷新当前编辑页面，请知悉。`
      );
      supplier_info = {
        goods_sku_supplier: {
          id: form.value.id,
          goods_sku_identification_processing: identification_processing,
        },
      };
      break;
    default:
      break;
  }
  regionSave({ ...data, ...supplier_info });
};

// 区域保存
const regionSave = async (data) => {
  try {
    const res = await goodsRegionSave(data);
    ElMessage.success("保存成功");
    close();
    emit("queryDetail");
  } catch (e) {
    throw Error(e);
  }
};

// 初始化报关信息
const initCustomsInfo = () => {
  return {
    cn_name: "",
    en_name: "",
    cn_material: "",
    en_material: "",
    customs_code: "",
    declare_unit: "",
    customs_quantity: "",
    purpose: "",
    tax_rebate_rate: "",
    is_multi_platform: "",
    declare_elements_list: [{}],
    goods_sku_customs_info: [
      {
        customs_currency: "USD",
      },
    ],
    declare_elements: "",
  };
};

// 报关信息自动填充
const onAutoFill = () => {
  TradeAgentRef.value.onAutoFill();
};
</script>
<style scoped lang="scss">
.view {
  .el-form-item {
    width: 100% !important;
  }
  .flex-wrap {
    display: grid !important;
    grid-template-columns: repeat(4, minmax(0, 1fr)) !important;
  }

  :deep(.el-form-item__label) {
    color: #999999;
    font-weight: 400;
  }
}
</style>
